package com.htj.bookreview.contorller;

import com.htj.bookreview.entity.User;
import com.htj.bookreview.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class UserController {

    @Autowired
    UserService service;

    @RequestMapping("/users")
    public String showUsers(ModelMap modelMap){
        List<User> list= service.queryAllUser();
        modelMap.addAttribute("list",list);
        return "users";
    }

    @RequestMapping("/addUser")
    @ResponseBody
    public Map addUser(User user){
        int flag = service.addUser(user);
        Map<String,Object> map = new HashMap<>();
        if (flag ==1){
            map.put("msg","用户新增成功！");
            return map;
        }else {
            map.put("msg","用户新增失败！");
            return map;
        }
    }

    @RequestMapping(value = "/deleteUser+{id}")
    public String dropUser(@PathVariable("id") String id, ModelMap modelMap){
        int flag = service.dropUser(id);
        List<User> userList = service.queryAllUser();
        modelMap.addAttribute("userList",userList);
        if (flag ==1){
            return "users";
        }else {
            return "error";
        }
    }

    @RequestMapping("/user+{id}")
    public String queryUser(@PathVariable ("id") String id, ModelMap modelMap){
        User user = service.queryUserById(id);
        modelMap.addAttribute("user",user);
        return "userInfo";
    }

    @RequestMapping("/modifyUser")
    @ResponseBody
    public Map modifyUser(User user){
        int flag = service.modifyUser(user);
        Map<String,Object> map = new HashMap<>();
        if (flag == 1){
            map.put("msg","修改成功！");
            return map;
        }else {
            map.put("msg","修改失败！");
            return map;
        }
    }

    @ResponseBody
    @RequestMapping("/getAll")
    public List<User> get(){
        List<User> userList = service.queryAllUser();
        return userList;
    }
}
